import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, Popconfirm, message, Modal, Select  } from 'antd'
import _ from 'lodash'

import { areaLevelCode, areaTypeCode, confirmDelete } from 'lib/config'
import Ajax from 'lib/Ajax'

const ButtonGroup = Button.Group;
const FormItem = Form.Item;


class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      editType: "",
      rowdata: {},
      data: []
    }
    // 翻页相关
    this.current = 1;   //当前第几页
    this.total = 10;   //总共多少页
    this.pageSize = 10;   //每页多少行
  }

  componentDidMount(){
    this.loadData();
  }

  componentWillReceiveProps(nextProps){
    var self = this;
    this.current = 1;
    self.loadData();
  }

  loadData = ()=>{
    var self = this;

    self.setState({
      loading: true
    });

    Ajax({
      url: '/role/list',
      data: {
        "roleCode": self.props.search.roleCode,
        "roleName": self.props.search.roleName,
        "currentPage": self.current,  //请求页码
        "perPage": self.pageSize,   //每页数量
      },
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(this.current*this.pageSize/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }
  // 操作
  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: row
      });
    }else{
      this.setState({
        visible: true,
        editType: 'new'
      });
    }
  }

  setting = ()=>{

  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var area = _.find(this.state.data, function(chr){
        return chr.id == rowdata.id;
      })
      Object.assign(area, {
        roleCode: rowdata.roleCode,
        roleName: rowdata.roleName,
      });
      self.setState({
        visible: false,
        rowdata: {},
        data: this.state.data
      });
      message.success('修改记录成功！');
    }else{
      self.setState({
        visible: false,
        rowdata: {}
      });
      message.success('增加记录成功！');
    }
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }

  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/role/delete',
        data: {
          "id": id
        },
        success: function(data){
          // this.setState()
          // console.log(data);
          // _.remove(self.state.data, function(d) {
          //   return d.id == id
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除角色');
    });
  }
  
  render() {
    var pagination = {
      current: this.current,
      total: this.total,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      pageSize: this.pageSize,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    const columns = [{
        title: '角色代码',
        dataIndex: 'roleCode'
      }, {
        title: '角色名称',
        dataIndex: 'roleName'
      },{
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Dropdown overlay={
              <Menu>
                <Menu.Item>
                  <a onClick={this.operate.bind(this, "edit", record)} href="javascript:;">编辑</a>
                </Menu.Item>
                <Menu.Item>
                  <a onClick={this.setting.bind(this, record)} href="javascript:;">权限设置</a>
                </Menu.Item>
                <Menu.Item>
                  <a href="javascript:;" onClick={this.doDelete.bind(this, record.id)} >删除</a>
                </Menu.Item>
              </Menu>
            }>
              <a className="ant-dropdown-link" href="#">
                操作 <Icon type="down" />
              </a>
            </Dropdown>
          </span>
        )
    }];

    return (
    	<div 
        className=""
      >
        <Table
          columns={ columns }
          dataSource={ this.state.data }
          pagination={ pagination }
          loading={this.state.loading}
          title={() => (<div>
                          <Button type="primary" style={{marginRight: 15}} icon="plus" onClick={ this.operate.bind(this, 'new') }>新建角色</Button>
                        </div>)}
        />
        <EditModule 
          visible={ this.state.visible }
          onOk={ this.editOk }
          onCancel={ this.editCancel }
          type={ this.state.editType }
          rowdata={ this.state.rowdata }
        />
    	</div>
    )
  }
}

module.exports = ModuleName






class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  componentWillReceiveProps(nextProps){
    this.props.form.resetFields();
  }

  handleCommit = () => {
    var self = this;
    this.props.form.validateFields((err, values) => {
      if(this.state.loading){
        return
      }
      self.setState({
        loading: true
      });
      const { type, rowdata, address  } = this.props;
      if(self.props.type == 'edit'){
        values.areaId = rowdata.areaId
      }else{
        values.areaParentId = address.areaCode
      }
      Ajax({
        url: '/role/save',
        data: values,
        success: function(data){
          this.setState({
            loading: false
          });
          self.props.onOk(self.props.type, data);
        },
        error: function(error){
          this.setState({
            loading: false
          });
          message.error(error);
        }
      });
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const { visible, type, rowdata, address  } = this.props;
    return (<Modal 
              title={ type == 'edit'?"编辑角色信息":"新建角色信息" } 
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="角色代码">
                        {getFieldDecorator("roleCode",{
                          initialValue: type == 'edit'?rowdata.roleCode:"",
                          rules: [{
                            required: true, message: '请输入角色代码',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="角色名称">
                        {getFieldDecorator("roleName",{
                          initialValue: type == 'edit'?rowdata.roleName:"",
                          rules: [{
                            required: true, message: '请输入角色名称',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20} className="area-modifier">
                    <Col span={24}>
                      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="备注">
                        {getFieldDecorator("remark",{
                          initialValue: type == 'edit'?rowdata.remark:"",
                        })(
                          <Input type="textarea"/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Spin>
            </Modal>);
  }
}
var EditModule = Form.create()(Edit);
